//
//  GYOnlyRefundViewController.m
//  GoodLuck
//
//  Created by apple on 2018/3/24.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYOnlyRefundViewController.h"
#import "GYNetWorkTools.h"

@interface GYOnlyRefundViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *storeNameLable;
@property (weak, nonatomic) IBOutlet UIImageView *goodsImageView;
@property (weak, nonatomic) IBOutlet UILabel *goodsNameLable;
@property (weak, nonatomic) IBOutlet UILabel *goodsPriceLable;
@property (weak, nonatomic) IBOutlet UILabel *goodsNumlable;
@property (weak, nonatomic) IBOutlet UILabel *imageDesLable;

@property (weak, nonatomic) IBOutlet UITextField *refundReasonTF;
@property (weak, nonatomic) IBOutlet UITextField *refundMoneyTF;
@property (weak, nonatomic) IBOutlet UITextField *refundDesTF;

/** 图片数据数组 */
@property (nonatomic, strong) NSMutableArray *imageDatas;
/** 当前选择的按钮 */
@property (nonatomic, strong) UIButton *currentSelectBtu;

@property (weak, nonatomic) IBOutlet UIButton *subBtu;

/** 缓存图片名字数据 */
@property (nonatomic, strong) NSMutableArray *imagesName;

@end

@implementation GYOnlyRefundViewController

//照片选择
- (IBAction)selectPhoto:(UIButton *)sender {
    self.currentSelectBtu = sender;

    NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.delegate = self;
    //1.获取系统相机支持的媒体格式 (这个参数不管填写什么都返回所有的支持格式)
    //设置你要支持的媒体格式
    ipc.mediaTypes = mediaTypes;

    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    
    UIAlertAction *cameraBtu = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:ipc animated:YES completion:nil];
        }
    }];
    
    UIAlertAction *libraryBtu = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
            //3.设置 图片或是视频的来源和支持的媒体格式
            //设置你数据的来源
            ipc.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            [self presentViewController:ipc animated:YES completion:nil];
        }
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击取消按钮/...");
    }];
    
    [alertController addAction:cameraBtu];
    [alertController addAction:libraryBtu];
    [alertController addAction:cancel];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

//提交退款申请
- (IBAction)sunRefundRequest:(UIButton *)sender {
    //首先上传图片
    if (self.imageDatas.count != 0) {
        for (NSData *imageData in self.imageDatas) {
            [GYNetWorkTools requestUploadRefundImageData:imageData success:^(NSDictionary *obj) {
                NSLog(@"image=======%@",obj);
                int code = [[obj objectForKey:@"code"] intValue];
                NSDictionary *datas = [obj objectForKey:@"datas"];
                if (code == 200) {
                    NSString *file_name = [datas objectForKey:@"file_name"];
                    [self.imagesName addObject:file_name];
                    if (self.imagesName.count == self.imageDatas.count) {
                        if (self.isRefund) {
                            [self loadRefundOrReturnGoods:@"1"];
                        }else {
                            [self loadRefundOrReturnGoods:@"2"];
                        }
                    }
                }else {
                    NSLog(@"upload====%@",[datas objectForKey:@"error"]);
                }
            } error:^(NSError *error) {
                NSLog(@"UploadRefundImageDataFailed====%@",error);
            }];
        }
    }else {
        if (self.isRefund) {
            [self loadRefundOrReturnGoods:@"1"];
        }else {
            [self loadRefundOrReturnGoods:@"2"];
        }
    }
}

- (void)loadRefundOrReturnGoods:(NSString *)type {
#warning 理由ID有待改
    if (self.if_refund_cancel == 1) {
        //代表全额退款
        [GYNetWorkTools requestRefundAllMoney:self.orderGoods.order_id buyer_message:self.refundDesTF.text refund_pic:self.imagesName success:^(NSDictionary *obj) {
            //NSLog(@"return======%@",obj);
            int code = [[obj objectForKey:@"code"] intValue];
            
            if (code == 200) {
                [EasyTextView showText:@"退款提交申请提交成功!"];
                [self.navigationController popToRootViewControllerAnimated:YES];
            }else if (code == 400) {
                [EasyTextView showText:[[obj objectForKey:@"datas"] objectForKey:@"error"]];
                NSLog(@"error=====%@",[[obj objectForKey:@"datas"] objectForKey:@"error"]);
            }
        } error:^(NSError *error) {
            [EasyTextView showText:@"亲,您的网络可能不太通畅,请稍后在操作!"];
        }];
    }else {
        //代表部分退款
        [GYNetWorkTools requestDeliverGoodsOrderRefund:self.orderGoods.order_id order_goods_id:self.orderGoods.rec_id refund_type:type reason_id:@"95" refund_amount:self.orderGoods.goods_price goods_num:self.orderGoods.goods_num buyer_message:self.refundDesTF.text refund_pic:self.imagesName success:^(NSDictionary *obj) {
            NSLog(@"returnGoods======%@",obj);
            int code = [[obj objectForKey:@"code"] intValue];
            
            if (code == 200) {
                [EasyTextView showText:@"退款提交申请提交成功!"];
                [self.navigationController popToRootViewControllerAnimated:YES];
            }else if (code ==  400) {
                [EasyTextView showText:[[obj objectForKey:@"datas"] objectForKey:@"error"]];
                NSLog(@"error=====%@",[[obj objectForKey:@"datas"] objectForKey:@"error"]);
            }
        } error:^(NSError *error) {
            [EasyTextView showText:@"亲,您的网络可能不太通畅,请稍后在操作!"];
        }];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

    //初始化
    [self setupUI];
}

- (void)setupUI {
    self.navigationItem.title = @"订单退款";

    self.subBtu.layer.cornerRadius = 4;
    [self.goodsImageView sd_setImageWithURL:[NSURL URLWithString:self.orderGoods.image_60_url] placeholderImage:[UIImage imageNamed:@"4"]];
    self.goodsNameLable.text = self.orderGoods.goods_name;
    self.goodsPriceLable.text = [NSString stringWithFormat:@"¥%@",self.orderGoods.goods_price];
    self.goodsNumlable.text = [NSString stringWithFormat:@"x%@",self.orderGoods.goods_num];
    self.imageDesLable.layer.cornerRadius = 4;
    self.imageDesLable.layer.masksToBounds = YES;
    
    //1.设置退款原因
    self.refundReasonTF.userInteractionEnabled = self.if_refund_cancel == 1 ? NO : YES;
    if (self.if_refund_cancel == 1) {
        self.refundReasonTF.text = @"取消订单，全额退款";
    }
    
    //2.监听说明textfiled
    [self.refundDesTF addTarget:self action:@selector(endEdit) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    //加载订单退款详情  设置店铺名字
    [EasyLodingView showLodingText:@"正在加载..." config:^EasyLodingConfig *{
        EasyLodingConfig *config = [EasyLodingConfig shared];
        config.showOnWindow = YES;
        
        return config;
    }];
    NSLog(@"self.orderGoods.order_id=====%@",self.orderGoods.order_id);
    //判断是订单退款和商品退款
    if (self.if_refund_cancel == 1) {//order_amount 退款原因  部分退款会返回一个原因列表   全额退款固定填  “取消订单，全额退款
        [GYNetWorkTools requestOrderALLRefundDetailInfo:self.orderGoods.order_id success:^(NSDictionary *obj) {
            //NSLog(@"all refund obj=======%@",obj);
            int code = [[obj objectForKey:@"code"] intValue];
            NSDictionary *datas = [obj objectForKey:@"datas"];
            NSDictionary *order = [datas objectForKey:@"order"];
            if (code == 200) {
                [EasyLodingView hidenLoingInView:[UIApplication sharedApplication].keyWindow];
                self.storeNameLable.text = [order objectForKey:@"store_name"];
                self.refundMoneyTF.text = [order objectForKey:@"refund_amount"];
            }else if (code == 400) {
                [EasyLodingView hidenLoingInView:[UIApplication sharedApplication].keyWindow];
                [EasyTextView showText:@"加载数据出错,请重新加载!"];
                NSLog(@"error====%@",[datas objectForKey:@"error"]);
            }
        } error:^(NSError *error) {
            [EasyLodingView hidenLoingInView:[UIApplication sharedApplication].keyWindow];
            [EasyTextView showText:@"加载数据出错,请重新加载!"];
            NSLog(@"OrderRefundOrderDetailsInfoFailed===%@",error);
        }];
    }else {
        //代表部分退款 goods_pay_price
        [GYNetWorkTools requestOrderRefundOrderDetailsInfo:self.orderGoods.order_id order_goods_id:self.orderGoods.rec_id success:^(NSDictionary *obj) {
            //NSLog(@"obj=======%@",obj);
            int code = [[obj objectForKey:@"code"] intValue];
            NSDictionary *datas = [obj objectForKey:@"datas"];
            NSDictionary *order = [datas objectForKey:@"order"];
            if (code == 200) {
                [EasyLodingView hidenLoingInView:[UIApplication sharedApplication].keyWindow];
                self.storeNameLable.text = [order objectForKey:@"store_name"];
                self.refundMoneyTF.text = [order objectForKey:@"refund_amount"];
            }else if (code == 400) {
                [EasyLodingView hidenLoingInView:[UIApplication sharedApplication].keyWindow];
                [EasyTextView showText:@"加载数据出错,请重新加载!"];
                NSLog(@"error====%@",[datas objectForKey:@"error"]);
            }
        } error:^(NSError *error) {
            [EasyLodingView hidenLoingInView:[UIApplication sharedApplication].keyWindow];
            [EasyTextView showText:@"加载数据出错,请重新加载!"];
            NSLog(@"OrderRefundOrderDetailsInfoFailed===%@",error);
        }];
    }
}

- (void)endEdit {
    [self.view endEditing:YES];
}

#pragma mark -- UIImagePickerControllerDelegate,UINavigationControllerDelegate

//适用获取所有媒体资源，只需判断资源类型
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //这里应该要给按钮设置图片和状态
    [self.currentSelectBtu setBackgroundImage:image forState:UIControlStateNormal];
    //把图片数据缓存起来  然后等待上传
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
    
    if (self.currentSelectBtu.selected) {
        [self.imageDatas replaceObjectAtIndex:self.currentSelectBtu.tag-1 withObject:data];
    }else {
        [self.imageDatas addObject:data];
    }
    self.currentSelectBtu.selected = YES;
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark -- 懒加载

- (NSMutableArray *)imageDatas {
    if (!_imageDatas) {
        _imageDatas = [NSMutableArray array];
    }
    
    return _imageDatas;
}

- (NSMutableArray *)imagesName {
    if (!_imagesName) {
        _imagesName = [NSMutableArray array];
    }
    
    return _imagesName;
}
@end
